<template>
    <!-- 操作按钮区域 -->
    <el-button plain type="primary" style="margin-bottom: 10px;" @click="Open()">添加</el-button>
    <!-- 批量删除按钮：当没有选中项时禁用，防止用户误操作 -->
    <el-button plain type="danger" style="margin-bottom: 10px; margin-left: 10px;" @click="batchDelete"
        :disabled="multipleSelection.length === 0">
        批量删除
    </el-button>
    <el-button plain type="primary" style="float: right;" @click="Open()">导出</el-button>

    <!-- 数据表格：支持多选和批量操作 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <!-- 选择列：用于批量操作的复选框 -->
        <el-table-column type="selection" width="55" />
        <el-table-column fixed type="index" label="序号" width="60" />
        <el-table-column prop="materialGroupCode" label="物料群组编码" width="150" />
        <el-table-column prop="materialGroupName" label="物料群组名称" width="150" />
        <el-table-column prop="materialGroupType" label="物料群组类型" width="180" />
        <el-table-column prop="materialGroupCount" label="物料群组数量" width="180" />
        <el-table-column prop="flowName" label="所属工艺" width="180" />
        <el-table-column prop="materialGroupDesc" label="物料群组描述" width="180" />
        <el-table-column prop="createrPeople" label="创建人" width="130" />
        <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.updateTime).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
                <el-button link type="warning" @click="OpenUpdate(scope.row)">编辑</el-button>
                <el-button link type="danger" @click="Del(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 添加物料群组弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加物料群组" width="500px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
            <el-form-item label="产线编码" prop="materialGroupCode">
                <el-input v-model="ruleForm.materialGroupCode" placeholder="请输入物料群组编码" />
            </el-form-item>
            <el-form-item label="产线名称" prop="materialGroupName">
                <el-input v-model="ruleForm.materialGroupName" placeholder="请输入产线名称" />
            </el-form-item>
            <el-form-item label="物料群组类型" prop="materialGroupType">
                <el-select v-model="ruleForm.materialGroupType" placeholder="请选择物料群组类型">
                    <el-option label="成品" value="成品" />
                    <el-option label="半成品" value="半成品" />
                    <el-option label="原材料" value="原材料" />
                </el-select>
            </el-form-item>
            <el-form-item label="物料群组数量" prop="materialGroupCount">
                <el-input v-model="ruleForm.materialGroupCount" placeholder="请输入物料群组数量" />
            </el-form-item>
            <el-form-item label="所属工艺" prop="processFlowId">
                <el-select v-model="ruleForm.processFlowId" placeholder="请选择所属工艺">
                      <el-option v-for="item in gy" :label="item.flowName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="物料群组描述" prop="materialGroupDesc">
                <el-input v-model="ruleForm.materialGroupDesc" type="textarea" placeholder="请输入物料群组描述" />
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 修改物料群组弹窗 -->
    <el-dialog v-model="dialogVisibleUpdate" title="修改物料群组" width="500px">
        <el-form ref="ruleFormRef" :model="ruleFormUpdate" :rules="rules" label-width="120px">
            <el-form-item label="产线编码" prop="materialGroupCode">
                <el-input v-model="ruleFormUpdate.materialGroupCode" placeholder="请输入物料群组编码" />
            </el-form-item>
            <el-form-item label="产线名称" prop="materialGroupName">
                <el-input v-model="ruleFormUpdate.materialGroupName" placeholder="请输入产线名称" />
            </el-form-item>
            <el-form-item label="物料群组类型" prop="materialGroupType">
                <el-select v-model="ruleFormUpdate.materialGroupType" placeholder="请选择物料群组类型">
                    <el-option label="成品" value="成品" />
                    <el-option label="半成品" value="半成品" />
                    <el-option label="原材料" value="原材料" />
                </el-select>
            </el-form-item>
            <el-form-item label="物料群组数量" prop="materialGroupCount">
                <el-input v-model="ruleFormUpdate.materialGroupCount" placeholder="请输入物料群组数量" />
            </el-form-item>
            <el-form-item label="所属工艺" prop="processFlowId">
                <el-select v-model="ruleFormUpdate.processFlowId" placeholder="请选择所属工艺">
                    <el-option v-for="item in gy" :label="item.flowName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="物料群组描述" prop="materialGroupDesc">
                <el-input v-model="ruleFormUpdate.materialGroupDesc" type="textarea" placeholder="请输入物料群组描述" />
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!--分页-->
    <div class="pagination-container">
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[3, 6, 9, 12]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="custom-pagination" />
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import { fr, pa } from 'element-plus/es/locales.mjs';
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
const pinia = useCounterStore();
const tableData = ref([]) // 物料群组表格数据
const multipleSelection = ref<any[]>([]) // 存储用户选中的表格行数据，用于批量操作

//物料群组向后端传参
const page = reactive({
    PageIndex: 1,
    PageSize: 5,
    totalcount: 0
})

//钩子
onMounted(() => {
    GetWorkShop()
    GetMaterialGroup()
})
const gy = ref([{
 // 工艺数据，用于物料群组关联工艺的下拉选择
    "id": 722079442591761,
    "flowName": "",

}])
//工艺向后端传参
const pagegy = reactive({
    PageIndex: 1,
    PageSize: 100,
    totalcount: 0
})
//工艺网络传出
const GetWorkShop = () => {
    axios.get('/api/ProcessFlow/GetProcessFlows', { params: pagegy }).then(res => {
        if (res.data.code == 200) {
            gy.value = res.data.totalPage
            console.log(gy)
            pagegy.totalcount = res.data.totalcount
        }
    })
}
//物料群组网络传输
const GetMaterialGroup = () => {
    axios.get('/api/MaterialManagement/GetMaterialGroup', { params: page }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.totalPage
            page.totalcount = res.data.totalcount
        }
    })
}
// 控制弹窗显示
const dialogVisible = ref(false);
const Open = () => {
    dialogVisible.value = true;
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "materialGroupCode": "",
    "materialGroupName": "",
    "materialGroupType": "",
    "materialGroupCount": null,
    "processFlowId": null,
    "materialGroupDesc": "",
    "createrPeople": pinia.piniaDto.accountName
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    materialGroupCode: [
        { required: true, message: '请输入物料群组编码', trigger: 'blur' },
    ],
    materialGroupName: [
        {
            required: true,
            message: '请输入物料群组名称',
            trigger: 'blur',
        },
    ],
    materialGroupType: [
        {
            required: true,
            message: '请选择物料群组类型',
            trigger: 'blur',
        },
    ],
    materialGroupCount: [
        {
            required: true,
            message: '请输入物料群组数量',
            trigger: 'blur',
        },
    ],
    processFlowId: [
        {
            required: true,
            message: '请选择工艺',
            trigger: 'blur',
        }],
    materialGroupDesc: [
        {
            required: true,
            message: '请输入物料群组描述',
            trigger: 'blur',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post('/api/MaterialManagement/AddMaterialGroup', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);

                    dialogVisible.value = false;
                    GetMaterialGroup(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    page.PageSize = val;
    GetMaterialGroup()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    page.PageIndex = val;
    GetMaterialGroup()
}
const dialogVisibleUpdate = ref(false);
const OpenUpdate = (row: any) => {
    dialogVisibleUpdate.value = true
    ruleFormUpdate.id = row.id
    ruleFormUpdate.materialGroupCode = row.materialGroupCode
    ruleFormUpdate.materialGroupName = row.materialGroupName
    ruleFormUpdate.materialGroupType = row.materialGroupType
    ruleFormUpdate.materialGroupCount = row.materialGroupCount
    ruleFormUpdate.processFlowId = row.processFlowId
    ruleFormUpdate.materialGroupDesc = row.materialGroupDesc
}
const ruleFormUpdate = reactive({
    "id": null,
    "materialGroupCode": "",
    "materialGroupName": "",
    "materialGroupType": "",
    "processFlowId": null,
    "materialGroupCount": null,
    "materialGroupDesc": "",
    "updaterPeople": pinia.piniaDto.accountName
})
//修改网络
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.put('/api/MaterialManagement/UpdateMaterialGroup', ruleFormUpdate).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisibleUpdate.value = false;
                    GetMaterialGroup(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const Del = (id: any) => {
    ElMessageBox.confirm(
        '确定要删除该产线吗？删除后数据将无法恢复。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post(`/api/MaterialManagement/DelMaterialGroup`, { id: id }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetMaterialGroup(); // 删除成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message);
                }
            }).catch(error => {
                ElMessage.error('删除失败，请重试');
                console.error('Delete error:', error);
            });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}

/**
 * 批量选择处理函数
 * 当用户在表格中选择/取消选择行时触发
 * @param val 当前选中的所有行数据数组
 */
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
}

/**
 * 批量删除功能
 * 删除用户选中的多条物料群组记录
 * 包含数据验证、用户确认、API调用、结果处理等完整流程
 */
const batchDelete = () => {
    // 1. 数据验证：检查是否有选中的数据
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的数据');
        return;
    }

    // 2. 提取选中行的ID数组，用于后端删除操作
    const ids = multipleSelection.value.map((item: any) => item.id);

    // 3. 显示确认对话框，防止用户误操作
    ElMessageBox.confirm(
        `确定要删除选中的 ${multipleSelection.value.length} 条物料群组记录吗？删除后数据将无法恢复。`,
        '批量删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning', // 警告类型的对话框
        }
    )
        .then(() => {
            // 4. 用户确认删除，调用后端批量删除接口
            axios.post('/api/MaterialManagement/DelMaterialGroup', {
                id: 0,        // 单个删除时使用，批量删除时设为0
                ids: ids      // 要删除的ID数组
            }).then(res => {
                // 5. 处理删除结果
                if (res.data.code == 200) {
                    // 删除成功
                    ElMessage.success(res.data.message);
                    GetMaterialGroup(); // 重新获取数据，刷新表格显示
                    multipleSelection.value = []; // 清空选择状态，重置UI
                } else {
                    // 删除失败，显示服务器返回的错误信息
                    ElMessage.error(res.data.message);
                }
            }).catch(error => {
                // 6. 处理网络错误或其他异常
                ElMessage.error('批量删除失败，请重试');
                console.error('Batch delete error:', error);
            });
        })
        .catch(() => {
            // 7. 用户取消删除操作
            ElMessage.info('已取消批量删除');
        });
}
</script>

<style scoped>
.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px;
    background-color: #f9fafb;
    border-radius: 8px;
}

.custom-pagination {
    --el-pagination-item-size: 32px;
    --el-pagination-item-bg: #ffffff;
    --el-pagination-item-color: #606266;
    --el-pagination-item-hover-color: #4096ff;
    --el-pagination-item-active-color: #ffffff;
    --el-pagination-item-active-bg: #4096ff;
    --el-pagination-border-radius: 6px;
    --el-pagination-margin: 0 5px;
}

.custom-pagination .el-pagination__prev,
.custom-pagination .el-pagination__next {
    width: 32px;
    height: 32px;
    border-radius: 6px;
}

.custom-pagination .el-pagination__sizes {
    margin-right: 10px;
}

.custom-pagination .el-pagination__total {
    margin-right: 10px;
    color: #606266;
}

.custom-pagination .el-pagination__item {
    margin: 0 5px;
    border-radius: 6px;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
}

.custom-pagination .el-pagination__item:hover {
    background-color: #f0f5ff;
}

.custom-pagination .el-pagination__item.is-active {
    background-color: #4096ff;
    color: #ffffff;
}
</style>
